<template>
  <div class="supplier-billing-management">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>我的对账单管理</span>
        </div>
      </template>

      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" size="small">
          <el-form-item label="对账单状态">
            <el-select v-model="searchForm.status" placeholder="全部">
              <el-option label="全部" value=""></el-option>
              <el-option label="待确认" value="pending"></el-option>
              <el-option label="已确认" value="confirmed"></el-option>
              <el-option label="有争议" value="disputed"></el-option>
              <el-option label="已结算" value="settled"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchBillings">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 对账单列表 -->
      <el-table v-loading="loading" :data="billingList.records" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="statementNo" label="对账单编号" width="180"></el-table-column>
        <el-table-column prop="startDate" label="开始日期"></el-table-column>
        <el-table-column prop="endDate" label="结束日期"></el-table-column>
        <el-table-column prop="totalAmount" label="总金额" formatter="formatCurrency"></el-table-column>
        <el-table-column prop="commissionAmount" label="佣金金额" formatter="formatCurrency"></el-table-column>
        <el-table-column prop="paymentAmount" label="实付金额" formatter="formatCurrency"></el-table-column>
        <el-table-column prop="statusDesc" label="状态"></el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template slot-scope="scope">
            <el-button size="small" @click="viewDetail(scope.row.id)">查看详情</el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="small"
              type="primary"
              @click="confirmBilling(scope.row.id)"
            >
              确认
            </el-button>
            <el-button
              v-if="scope.row.status === 'pending'"
              size="small"
              type="danger"
              @click="disputeBilling(scope.row.id)"
            >
              有争议
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model="pagination.pageNum"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="billingList.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 对账单详情弹窗 -->
    <el-dialog :visible.sync="detailDialogVisible" title="对账单详情" width="80%">
      <div v-if="billingDetail" class="billing-detail">
        <div class="detail-header">
          <div class="detail-item"><span class="label">对账单编号：</span>{{ billingDetail.statementNo }}</div>
          <div class="detail-item"><span class="label">供应商名称：</span>{{ billingDetail.supplierName }}</div>
          <div class="detail-item"><span class="label">对账周期：</span>{{ billingDetail.startDate }} 至 {{ billingDetail.endDate }}</div>
          <div class="detail-item"><span class="label">总金额：</span>{{ formatCurrency(billingDetail.totalAmount) }}</div>
          <div class="detail-item"><span class="label">佣金金额：</span>{{ formatCurrency(billingDetail.commissionAmount) }}</div>
          <div class="detail-item"><span class="label">实付金额：</span>{{ formatCurrency(billingDetail.paymentAmount) }}</div>
          <div class="detail-item"><span class="label">状态：</span>{{ billingDetail.statusDesc }}</div>
          <div class="detail-item"><span class="label">备注：</span>{{ billingDetail.remark }}</div>
        </div>

        <div class="detail-title">对账单明细</div>
        <el-table :data="billingItems.records" style="width: 100%">
          <el-table-column prop="orderNo" label="订单编号"></el-table-column>
          <el-table-column prop="orderTime" label="订单时间"></el-table-column>
          <el-table-column prop="productName" label="商品名称"></el-table-column>
          <el-table-column prop="quantity" label="数量"></el-table-column>
          <el-table-column prop="unitPrice" label="单价" formatter="formatCurrency"></el-table-column>
          <el-table-column prop="totalPrice" label="总价" formatter="formatCurrency"></el-table-column>
          <el-table-column prop="commissionRate" label="佣金率" formatter="formatPercent"></el-table-column>
          <el-table-column prop="commissionAmount" label="佣金金额" formatter="formatCurrency"></el-table-column>
          <el-table-column prop="notes" label="备注"></el-table-column>
        </el-table>

        <div class="pagination-container">
          <el-pagination
            v-model="itemPagination.pageNum"
            :page-size="itemPagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="billingItems.total"
            @size-change="handleItemSizeChange"
            @current-change="handleItemCurrentChange"
          ></el-pagination>
        </div>
      </div>
      <div v-else>加载中...</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>

    <!-- 争议弹窗 -->
    <el-dialog :visible.sync="disputeDialogVisible" title="提交争议" width="500px">
      <el-form :model="disputeForm" ref="disputeForm" :rules="disputeRules">
        <el-form-item label="争议原因" prop="reason">
          <el-input type="textarea" v-model="disputeForm.reason" placeholder="请输入争议原因"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="disputeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDispute">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import unifiedBillingApi from '@/api/unifiedBillingApi'
import { mapGetters } from 'vuex'

export default {
  name: 'SupplierBillingManagement',
  data() {
    return {
      loading: false,
      searchForm: {
        status: ''
      },
      pagination: {
        pageNum: 1,
        pageSize: 10
      },
      billingList: {
        total: 0,
        records: []
      },
      detailDialogVisible: false,
      billingDetail: null,
      itemPagination: {
        pageNum: 1,
        pageSize: 10
      },
      billingItems: {
        total: 0,
        records: []
      },
      disputeDialogVisible: false,
      currentDisputeId: null,
      disputeForm: {
        reason: ''
      },
      disputeRules: {
        reason: [
          { required: true, message: '请输入争议原因', trigger: 'blur' },
          { min: 5, max: 500, message: '长度在 5 到 500 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['userType', 'isLoggedIn'])
  },
  created() {
    // 检查登录状态
    if (!this.isLoggedIn) {
      this.$router.push('/login')
      return
    }
    // 设置用户类型到API服务
    unifiedBillingApi.setUserType(this.userType)
    this.fetchBillings()
  },
  methods: {
    fetchBillings() {
      this.loading = true
      unifiedBillingApi
        .getBillingList(
          this.pagination.pageNum,
          this.pagination.pageSize,
          { status: this.searchForm.status }
        )
        .then((res) => {
          this.billingList = res.data
        })
        .catch((error) => {
          console.error('获取对账单列表失败:', error)
          this.$message.error('获取对账单列表失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    resetSearch() {
      this.searchForm = {
        status: ''
      }
      this.fetchBillings()
    },

    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.fetchBillings()
    },

    handleCurrentChange(current) {
      this.pagination.pageNum = current
      this.fetchBillings()
    },

    viewDetail(id) {
      this.detailDialogVisible = true
      this.loading = true
      unifiedBillingApi
        .getBillingDetail(id)
        .then((res) => {
          this.billingDetail = res.data
          // 加载对账单明细
          this.fetchBillingItems(id)
        })
        .catch((error) => {
          console.error('获取对账单详情失败:', error)
          this.$message.error('获取对账单详情失败')
        })
        .finally(() => {
          this.loading = false
        })
    },

    fetchBillingItems(statementId) {
      unifiedBillingApi
        .getBillingItems(
          statementId,
          this.itemPagination.pageNum,
          this.itemPagination.pageSize
        )
        .then((res) => {
          this.billingItems = res.data
        })
        .catch((error) => {
          console.error('获取对账单明细失败:', error)
          this.$message.error('获取对账单明细失败')
        })
    },

    handleItemSizeChange(size) {
      this.itemPagination.pageSize = size
      this.fetchBillingItems(this.billingDetail.id)
    },

    handleItemCurrentChange(current) {
      this.itemPagination.pageNum = current
      this.fetchBillingItems(this.billingDetail.id)
    },

    confirmBilling(id) {
      this.$confirm('确认对账单无误吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.loading = true
          unifiedBillingApi
            .confirmBilling(id)
            .then(() => {
              this.$message.success('对账单确认成功')
              this.fetchBillings()
            })
            .catch((error) => {
              console.error('确认对账单失败:', error)
              this.$message.error('确认对账单失败')
            })
            .finally(() => {
              this.loading = false
            })
        })
        .catch(() => {
          // 取消操作
        })
    },

    disputeBilling(id) {
      this.currentDisputeId = id
      this.disputeForm = {
        reason: ''
      }
      this.disputeDialogVisible = true
    },

    submitDispute() {
      this.$refs.disputeForm.validate((valid) => {
        if (valid) {
          this.loading = true
          unifiedBillingApi
            .disputeBilling(this.currentDisputeId, this.disputeForm.reason)
            .then(() => {
              this.$message.success('争议提交成功')
              this.disputeDialogVisible = false
              this.fetchBillings()
            })
            .catch((error) => {
              console.error('提交争议失败:', error)
              this.$message.error('提交争议失败')
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },

    formatCurrency(row, column, cellValue) {
      if (!cellValue) return '¥0.00'
      return '¥' + cellValue.toFixed(2)
    },

    formatPercent(row, column, cellValue) {
      if (!cellValue) return '0%'
      return (cellValue * 100).toFixed(2) + '%'
    }
  },
  watch: {
    // 监听用户类型变化
    userType(newValue) {
      unifiedBillingApi.setUserType(newValue)
    }
  }
}
</script>

<style scoped>
.supplier-billing-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.billing-detail {
  padding: 10px;
}

.detail-header {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.detail-item {
  width: 50%;
  margin-bottom: 10px;
}

.label {
  font-weight: bold;
  margin-right: 10px;
}

.detail-title {
  font-size: 16px;
  font-weight: bold;
  margin: 15px 0;
}
</style>